package getter

import (
	"context"

	"gitee.com/mesh_cpn/mesh.cpn.aphros/client"
)

type Marshaller[T any] func([]byte, T) error

type Caster[T any] func(T) T

type ConfigGetter[T any] struct {
	client.ConfigClient
	Caster[T]
	Marshaller[T]
}

func (g *ConfigGetter[T]) Get(ctx context.Context, key string) (T, error) {
	if g.Caster == nil {
		g.Caster = func(t T) T {
			return t
		}
	}
	if len(key) == 0 {
		return nil, nil
	}
	v, err := g.ConfigClient.Get(ctx, key)
	if err != nil {
		return nil, err
	}
	var res T
	err = g.Marshaller([]byte(v), res)
	if err != nil {
		return nil, err
	}
	return g.Caster(res), nil
}
